# !usr/bin/env python
# -*- coding:utf-8 _*-
"""
@Author:张广勤
@Web site: https://www.tunan.wang
@Github:www.github.com
 
@File:pyqt502.py
@Time:2022/3/8 11:10

@Motto:不积跬步无以至千里，不积小流无以成江海！
"""
'''
导入PySide2,mybor03---Mybor对象,relist
'''
from PySide2.QtWidgets import QApplication, QMessageBox,QTreeWidgetItem,QInputDialog
from PySide2.QtUiTools import QUiLoader
from mybro03 import Mybro
import os
import time
import threading
import multiprocessing as mp
from relist import year,year_list,halfyear_list,quarter_list,month_list,reverse_split,item_list

'''
定义类：Stats
QUiLoader().load()加载界面UI
'''
class Stats:

    def __init__(self):
        # 从文件中加载UI定义

        # 从 UI 定义中动态 创建一个相应的窗口对象
        # 注意：里面的控件对象也成为窗口对象的属性了
        # 比如 self.ui.button , self.ui.textEdit
        self.ui = QUiLoader().load('ui\jywf02.ui')
        # self.dan=0
        #读取csv,加载到界面，str1-eval--字典--values--list列表
        with open('zdmulu.csv','r',encoding='u8') as f:
            str1=f.read()#文件读取得到字符串
            dict_zd=eval(str1)#字符串转字典
            zdlist=list(dict_zd.values())#字典值转列表
        #self.ui.co
        #self.ui.comboBoxzd.addItems(zdlist)
        str2 = str(os.listdir(r'chaxunmulu'))#该目录下文件列表，转字符串
        print(str2)
        for li in zdlist:
            if str2.find(li) != -1:#查询目录已有之前的查询结果
                self.ui.comboBoxzd.addItem(li)
                #设置下拉组合框字体格式,不是某项条目的字体！
                self.ui.comboBoxzd.setFont('SimHei')
            else:
                self.ui.comboBoxzd.addItem(li)
        # self.ui.comboBoxzd.setFont('SimHei')
        #默认项22--2022年一套表制度
        self.ui.comboBoxzd.setCurrentIndex(22)
        #设置树控件2列
        self.ui.treeWidget_ml.setColumnCount(2)
        #设置树控件头部标签
        self.ui.treeWidget_ml.setHeaderLabels(['Key', 'Value'])
        #当前选中项
        self.item = self.ui.comboBoxzd.currentText()

        with open(f"chaxunmulu\{self.item}.csv", 'r', encoding='u8') as f:
            mulu = f.read()
            self.dict1 = eval(mulu)
        for k, v in self.dict1.items():
            if len(k) == 1:
                root = QTreeWidgetItem(self.ui.treeWidget_ml)
                root.setText(0, v)
                root.setText(1, k)
            elif len(k) == 3:
                child = QTreeWidgetItem(root)
                child.setText(0, v[0])
                child.setText(1, k)
            elif len(k) == 5:
                if v != '选择查询模板':
                    child1 = QTreeWidgetItem(child)
                    child1.setText(0, v)
                    child1.setText(1, k)

        self.ui.checkBox1.setChecked(True)

        self.ui.comboBoxzd.currentIndexChanged.connect(self.zdxz)
        self.ui.treeWidget_ml.clicked.connect(self.onTreeClicked)
        self.ui.pushButton_1.clicked.connect(self.xiazaicxml)
        self.ui.pushButton_2.clicked.connect(self.paqudata)
        #self.setCentralWidget(self.tree)

    #制度选择
    def zdxz(self):
        self.item = self.ui.comboBoxzd.currentText()
        self.ui.treeWidget_ml.clear()
        try:
            with open(f"chaxunmulu\{self.item}.csv", 'r', encoding='u8') as f:
                mulu = f.read()
                self.dict1 = eval(mulu)
            for k, v in self.dict1.items():
                if len(k) == 1:
                    root = QTreeWidgetItem(self.ui.treeWidget_ml)
                    root.setText(0, v)
                    root.setText(1, k)
                elif len(k) == 3:
                    child = QTreeWidgetItem(root)
                    child.setText(0, v[0])
                    child.setText(1, k)
                elif len(k) == 5:
                    if v != '选择查询模板':
                        child1 = QTreeWidgetItem(child)
                        child1.setText(0, v)
                        child1.setText(1, k)

        except:
            print('查询目录未下载，请先下载')
            QMessageBox.about(self.ui,
                              '下载',
                              f"\n\n"
                              f"{self.item}\n\n"
                              f"查询目录未下载，请先下载\t\t\t\t\t\n")

    def onTreeClicked(self):
        item = self.ui.treeWidget_ml.currentItem()
        print("key=%s ,value=%s" % (item.text(0), item.text(1)))
        # 截取item.text(1)前三位,得到报表
        # 截取item.text(1)第一位,得到周期
        if len(item.text(1)) == 5:
            zqcode = item.text(1)[:1]
            bbcode = item.text(1)[:3]
            print(type(bbcode))
            print('&'*50)
            #此item 非彼item
            zdcode=list({k for k, v in self.dict1.items() if v == self.item})[0]
            print(self.dict1[zdcode])
            print(self.dict1[zqcode])
            print(self.dict1[bbcode])
            print(self.dict1[bbcode][0])
            print(self.dict1[bbcode][1])

    def xiazaicxml(self):
        item=self.ui.comboBoxzd.currentText()
        print(item)
        # 如果文件已经存在,则让用户确认,否则,退出
        if os.path.exists(fr"chaxunmulu\{item}.csv"):
            print('查询目录已存在,是否重新下载?')
            q=QMessageBox.information(self.ui,'确认','查询目录已存在,是否重新下载?',
                                      QMessageBox.Yes|QMessageBox.No,QMessageBox.Yes)
            if q==16384:
                print('下载...')
                #bro.switchquery()
                bro.getchaxunmulu(item)
            else:
                print('取消')
        else:
            print('file not exist')
            #bro.switchquery()
            bro.getchaxunmulu(item)

    def paqudata(self):
        item=self.ui.treeWidget_ml.currentItem()
        print(item.text(0))
        print(item.text(1))
        if len(item.text(1))==5:
            zqcode = item.text(1)[:1]
            bbcode = item.text(1)[:3]
            #print(type(bbcode))
            #print('&' * 50)
            # 此item 非彼item
            zdcode = list({k for k, v in self.dict1.items() if v == self.item})[0]
            # print(self.dict1[zdcode])
            # print(self.dict1[zqcode])
            # print(self.dict1[bbcode])
            # print(self.dict1[bbcode][0])
            # print(self.dict1[bbcode][1])
            zd=self.dict1[zdcode]
            zq=self.dict1[zqcode]
            bb=self.dict1[bbcode]
            bb_name=self.dict1[bbcode][0]
            bb_code=self.dict1[bbcode][1]
            cx=item.text(0)
            print(zd,zq,bb,bb_name,bb_code,cx)
            print('开始爬取...')
            nian=year(zd)
            if zq=='年报':
                items = tuple(year_list(nian))
                item, ok = QInputDialog.getItem(self.ui, "select input dialog", "年份列表", items, 1, False)
                print(item,ok)
                cxlist=reverse_split(year_list(nian),item)
                print(f'查询列表{cxlist}')
                cxdangqi = item_list(year_list(nian), item)
                print(f'查询当期{cxdangqi}')
                print('爬取年报数据')
            elif zq=='季报':
                items = tuple(quarter_list(nian))
                item, ok = QInputDialog.getItem(self.ui, "select input dialog", "季度列表", items, 0, False)
                print(item, ok)
                cxlist = reverse_split(quarter_list(nian), item)
                print(f'查询列表{cxlist}')
                cxdangqi = item_list(quarter_list(nian), item)
                print(f'查询当期{cxdangqi}')
                print('爬取季报数据')
            elif zq=='月报':
                items = tuple(month_list(nian))
                item, ok = QInputDialog.getItem(self.ui, "select input dialog", "月份列表", items, 0, False)
                print(item, ok)
                cxlist = reverse_split(month_list(nian), item)
                print(f'查询列表{cxlist}')
                cxdangqi=item_list(month_list(nian),item)
                print(f'查询当期{cxdangqi}')
                print('爬取月报数据')
                #bro.switchquery()
                bro.paqudata(zd,zq,bb_code,cx)
                #self.dan设置一个变量
                # if self.dan:
                if self.ui.checkBox1.isChecked():
                    #查询当期,一个月的数据,直接"w"写入,以前有文件重写
                    bro.getdata1(cxdangqi,cx)
                else:
                    start_time=time.time()
                    # added_thread=threading.Thread(target=bro.getdata1,kwargs={'cxlist':cxlist,'chaxun':cx})
                    added_p = mp.Process(target=bro.getdata1, kwargs={'cxlist': cxlist, 'chaxun': cx})
                    #查询逐期，新建写入，后续追加
                    # bro.getdata1(cxlist,cx)
                    # added_thread.start()
                    # added_thread.join()
                    added_p.run()
                    # added_p.start()
                    # added_p.join()
                    end_time=time.time()
                    times=end_time-start_time
                    print(times)
            elif zq=='半年报':
                items = tuple(halfyear_list(nian))
                item, ok = QInputDialog.getItem(self.ui, "select input dialog", "半年度列表", items, 0, False)
                print(item, ok)
                cxlist = reverse_split(halfyear_list(nian), item)
                print(f'查询列表{cxlist}')
                cxdangqi = item_list(halfyear_list(nian), item)
                print(f'查询当期{cxdangqi}')
                print('爬取半年报数据')
            # bro.switchquery()
            # bro.paqudata(zd,zq,bb_code,cx)

        else:
            QMessageBox.about(self.ui,
                              '请选择到具体查询项目',
                              f"{item.text(0)}\t\t\t\t\t\n\n"
                              f"{item.text(1)}\n\n")


app = QApplication([])
bro=Mybro('140700zgq','071726zgq001!')
#bro=Mybro('140700czw','lwzb*123!')

stats = Stats()
stats.ui.show()
app.exec_()
bro.closewindow()
